package com.hzhr.iot.web.controller;

import com.hzhr.iot.core.util.HzhrDateUtil;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.device.sdk.service.Device_CollectDevice1Service;
import com.hzhr.iot.device.sdk.service.Device_CollectDeviceType_DesService;
import com.hzhr.iot.statis.sdk.model.deviceDataStatisExceptionReport.DeviceDataStatisExceptionReportModel;
import com.hzhr.iot.statis.sdk.model.deviceMonthlyGasConsume.dataSum.DeviceMonthlyGasConsumeDataSumModel;
import com.hzhr.iot.statis.sdk.service.Statis_DeptMonthlyGasConsumeService;
import com.hzhr.iot.statis.sdk.service.Statis_DeviceDataStatisExceptionReportService;
import com.hzhr.iot.statis.sdk.service.Statis_DeviceMonthlyGasConsumeService;
import com.hzhr.iot.user.sdk.model.dept.DeptModel;
import com.hzhr.iot.user.sdk.service.User_DeptService;
import com.hzhr.iot.web.Global;
import com.hzhr.iot.web.constant.DeviceOptions;
import com.hzhr.iot.web.dao_sm.SmDao;
import com.hzhr.iot.web.util.ExportExcel;
import com.hzhr.iot.web.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class ExportController {
    @Autowired
    User_DeptService user_deptService;
    @Autowired
    Statis_DeptMonthlyGasConsumeService statis_deptMonthlyGasConsumeService;
    @Autowired
    Global global;
    @Autowired
    Statis_DeviceMonthlyGasConsumeService statis_deviceMonthlyGasConsumeService;
    @Autowired
    DeviceOptions deviceOptions;
    @Autowired
    Device_CollectDeviceType_DesService device_collectDeviceType_desService;
    @Autowired
    Device_CollectDevice1Service device_collectDevice1Service;
    @Autowired
    Statis_DeviceDataStatisExceptionReportService statis_deviceDataStatisExceptionReportService;
    @Autowired
    SmDao smDao;

    @RequestMapping(value = "/export1", method = RequestMethod.GET)
    void export1(@RequestParam("month") String month, HttpServletResponse response) throws Exception {
        String title = month + "统计数据";
        Date monthDate = HzhrDateUtil.strToDate(month, "yyyy-MM");
        Date nextMonthDate = HzhrDateUtil.addMonth(monthDate, 1);
        String[] rowsName = new String[]{"分公司","流量计改造数量","流量计用气量", "GPRS物联网表改造数量", "GPRS物联网表用气量", "LORA表改造数量", "LORA表用气量",  "BK表改造数量", "BK表用气量"};
        List<Object[]> dataList = new ArrayList<Object[]>();

        Map<String, String> header = new HashMap<>();
        header.put("token", global.getToken());
        Map<String, Object> query = new HashMap<>();
        query.put("_equal_level", 2);
        query.put("_show", "list");
        query.put("_is_paging", false);
        query.put("_show_info", true);
        List<DeptModel> deptModels = user_deptService.get(header, query).getModelList();
        List<DeptModel> deptModelsTmp = new ArrayList<>();
        for (DeptModel deptModel :
        deptModels) {
            if ("渝中分公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("江北分公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("南岸分公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("九龙坡分公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("沙坪坝分公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("北碚分公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("大渡口分公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("两江公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("巴南公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("渝长公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("璧山公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("江津公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("梁平子公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("永川公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("忠县公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("大足子公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("合川公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("丰都子公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("中梁山子公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("涪陵子公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("开县子公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("长南燃气输配公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }
        for (DeptModel deptModel :
                deptModels) {
            if ("城口公司".equals(deptModel.getName())) {
                deptModelsTmp.add(deptModel);
                break;
            }
        }

        for (DeptModel deptModel :
                deptModelsTmp) {
            String deptName = deptModel.getName();
            if ("重庆燃气（贵州）公司".equals(deptName) ||
                    "渝燃公司".equals(deptName) ||
                    "中法能源公司".equals(deptName) ||
                    "压缩天然气公司".equals(deptName) ||
                    "工程建设中心".equals(deptName) ||
                    "永通股份公司".equals(deptName) ||
                    "供气分公司".equals(deptName) ||
                    "安装工程公司".equals(deptName) ||
                    "安装工程公司1".equals(deptName) ||
                    "管材分公司".equals(deptName) ||
                    "丰都公司".equals(deptName) ||
                    "管道维护公司".equals(deptName) ||
                    "开县公司".equals(deptName)) {
                continue;
            }

            //DTU
            query = new HashMap<>();
            query.put("_greaterthanorequal_date", monthDate.getTime());
            query.put("_lessthan_date", nextMonthDate.getTime());
            query.put("_like_collectDeviceResourceCode", deptModel.getResourceCode() + "%");
            List<String> gasUserCodes = new ArrayList<>();
            gasUserCodes.add("7176100391");
            gasUserCodes.add("7176100189");
            gasUserCodes.add("7176100290");
            gasUserCodes.add("7189869369");
            gasUserCodes.add("7201567220");
            gasUserCodes.add("7176100492");
            gasUserCodes.add("7176100088");
            gasUserCodes.add("7201567422");
            gasUserCodes.add("7176100896");
            gasUserCodes.add("3011750917");
            gasUserCodes.add("3012042169");
            gasUserCodes.add("3011753519");
            gasUserCodes.add("5066291284");
            gasUserCodes.add("5153655595");
            gasUserCodes.add("5131519987");
            gasUserCodes.add("7223843830");
            gasUserCodes.add("300300086");
            gasUserCodes.add("7188552917");
            gasUserCodes.add("7005959490");
            gasUserCodes.add("7240901329");
            gasUserCodes.add("7198577361");
            gasUserCodes.add("7002991543");
            gasUserCodes.add("7231884343");
            query.put("_notin_gasUserCode", gasUserCodes);
            query.put("_equal_collectDeviceCategoryCode", deviceOptions.getCode("COLLECT_DEVICE_CATEGORY", "FLOW_METER"));
            DeviceMonthlyGasConsumeDataSumModel dataSumModel_dtu = statis_deviceMonthlyGasConsumeService.getDataSum(header, query);
            query = new HashMap<>();
            query.put("_show_total", true);
            query.put("_lessthan_installTime", nextMonthDate.getTime());
            query.put("_like_resourceCode", deptModel.getResourceCode() + "%");
            query.put("_equal_categoryCode", deviceOptions.getCode("COLLECT_DEVICE_CATEGORY", "FLOW_METER"));
            int total_dtu = device_collectDevice1Service.get(header, query).getTotal();

            //GPRS物联网表
            query = new HashMap<>();
            query.put("_greaterthanorequal_date", monthDate.getTime());
            query.put("_lessthan_date", nextMonthDate.getTime());
            query.put("_lessthan_data", 1000);
            query.put("_like_collectDeviceResourceCode", deptModel.getResourceCode() + "%");
            query.put("_equal_collectDeviceCategoryCode", deviceOptions.getCode("COLLECT_DEVICE_CATEGORY", "GPRS_IOT_GAS_METER"));
            DeviceMonthlyGasConsumeDataSumModel dataSumModel_gprs = statis_deviceMonthlyGasConsumeService.getDataSum(header, query);
            query = new HashMap<>();
            query.put("_show_total", true);
            query.put("_lessthan_installTime", nextMonthDate.getTime());
            query.put("_like_resourceCode", deptModel.getResourceCode() + "%");
            query.put("_equal_categoryCode", deviceOptions.getCode("COLLECT_DEVICE_CATEGORY", "GPRS_IOT_GAS_METER"));
            int total_gprs = device_collectDevice1Service.get(header, query).getTotal();

            //LORA表
            query = new HashMap<>();
            query.put("_greaterthanorequal_date", monthDate.getTime());
            query.put("_lessthan_date", nextMonthDate.getTime());
            query.put("_lessthan_data", 500);
            query.put("_like_collectDeviceResourceCode", deptModel.getResourceCode() + "%");
            query.put("_equal_collectDeviceCategoryCode", deviceOptions.getCode("COLLECT_DEVICE_CATEGORY", "LORA_METER"));
            DeviceMonthlyGasConsumeDataSumModel dataSumModel_lora = statis_deviceMonthlyGasConsumeService.getDataSum(header, query);
            query = new HashMap<>();
            query.put("_show_total", true);
            query.put("_lessthan_installTime", nextMonthDate.getTime());
            query.put("_like_resourceCode", deptModel.getResourceCode() + "%");
            query.put("_equal_categoryCode", deviceOptions.getCode("COLLECT_DEVICE_CATEGORY", "LORA_METER"));
            int total_lora = device_collectDevice1Service.get(header, query).getTotal();

            //BK表
            query = new HashMap<>();
            query.put("_greaterthanorequal_date", monthDate.getTime());
            query.put("_lessthan_date", nextMonthDate.getTime());
            query.put("_lessthan_data", 1000);
            query.put("_like_collectDeviceResourceCode", deptModel.getResourceCode() + "%");
            query.put("_equal_collectDeviceCategoryCode", deviceOptions.getCode("COLLECT_DEVICE_CATEGORY", "LORA_METER"));
            DeviceMonthlyGasConsumeDataSumModel dataSumModel_bk = statis_deviceMonthlyGasConsumeService.getDataSum(header, query);
            query = new HashMap<>();
            query.put("_show_total", true);
            query.put("_lessthan_installTime", nextMonthDate.getTime());
            query.put("_like_resourceCode", deptModel.getResourceCode() + "%");
            query.put("_equal_categoryCode", deviceOptions.getCode("COLLECT_DEVICE_CATEGORY", "LORA_METER"));
            int total_bk = device_collectDevice1Service.get(header, query).getTotal();

            Object[] objects = new Object[]{deptModel.getName(),
                    total_dtu, new BigDecimal(dataSumModel_dtu.getDataSum()).intValue(),
                    total_gprs, new BigDecimal(dataSumModel_gprs.getDataSum()).intValue(),
                    total_lora, new BigDecimal(dataSumModel_lora.getDataSum()).intValue(),
                    total_bk, new BigDecimal(dataSumModel_bk.getDataSum()).intValue(),};

            dataList.add(objects);
        }

        ExportExcel ex = new ExportExcel(title, rowsName, dataList);
        String path= ex.export();
        if(!StringHelper.isTrimEmpty(path)){
            try {
                InputStream inStream = new FileInputStream(path);// 文件的存放路径
                // 设置输出的格式
                response.reset();
                response.setContentType("application/ms-excel;charset=UTF-8");
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sdf.format(date),"UTF-8")  + ".xls");
                // 循环取出流中的数据
                byte[] b = new byte[100];
                int len;
                try {
                    while ((len = inStream.read(b)) > 0)
                        response.getOutputStream().write(b, 0, len);
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping(value = "/export3", method = RequestMethod.GET)
    void export3(@RequestParam("day") String day, HttpServletResponse response) throws Exception {
        String title = day + "统计数据";
        String[] rowsName = new String[]{"采集设备编号","采集设备种类","物联网设备编号", "物联网设备种类", "燃气用户号", "燃气用户名称", "燃气用户地址",  "分公司", "管理站", "异常用量", "异常类型"};

        Map<String, String> header = new HashMap<>();
        header.put("token", global.getToken());
        Map<String, Object> query = new HashMap<>();
        query.put("_day", day);
        query.put("_show", "list");
        List<DeviceDataStatisExceptionReportModel> models = statis_deviceDataStatisExceptionReportService.get(header, query).getModelList();

        List<Object[]> dataList = new ArrayList<>();
        for (DeviceDataStatisExceptionReportModel model:
        models) {
            Object[] objects = new Object[]{model.getCollectDeviceCode(), model.getCollectDeviceCategoryDes(),
                    model.getIotDeviceCode(), model.getIotDeviceCategoryDes(), model.getGasUserCode(), model.getGasUserName(),
                    model.getGasUserAddress(), model.getSubCompanyName(), model.getManagementName(), model.getExceptionGasConsume(),
                    model.getExceptionTypeDes()
            };
            dataList.add(objects);
        }

        ExportExcel ex = new ExportExcel(title, rowsName, dataList);
        String path= ex.export();
        if(!StringHelper.isTrimEmpty(path)){
            try {
                InputStream inStream = new FileInputStream(path);// 文件的存放路径
                // 设置输出的格式
                response.reset();
                response.setContentType("application/ms-excel;charset=UTF-8");
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sdf.format(date),"UTF-8")  + ".xls");
                // 循环取出流中的数据
                byte[] b = new byte[100];
                int len;
                try {
                    while ((len = inStream.read(b)) > 0)
                        response.getOutputStream().write(b, 0, len);
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping(value = "/export4", method = RequestMethod.GET)
    void export4(@RequestParam("startDay") String startDay, @RequestParam("endDay") String endDay, HttpServletResponse response) throws Exception {
        String title = "集中器登录次数";
        List<String> days = HzhrDateUtil.getDayBetween(startDay, endDay);
        List<String> days1 = new ArrayList<>();
        days1.add("");
        for (String item :
        days ) {
            days1.add(item);
        }
        String[] rowsName = new String[days1.size()];
        days1.toArray(rowsName);

        List<Map<String, Object>> list = smDao.select3(startDay, endDay);

        Object[] objects = new Object[days.size() + 1];
        for(int i = 0; i < days.size() + 1; i++) {
            objects[i] = " ";
        }
        List<Object[]> dataList = new ArrayList<>();
        String currentCcrNo = null;
        for (Map<String, Object> item:
                list) {
            String ccrNo = HzhrTypeUtil.object2string(item.get("CCR_NO"));
            String time =  HzhrTypeUtil.object2string(item.get("T"));
            String count =  HzhrTypeUtil.object2string(item.get("C"));

            if (currentCcrNo == null) {
                currentCcrNo = ccrNo;
                objects[0] = ccrNo;
            }

            if (ccrNo.equals(currentCcrNo)) {
                if (days.contains(time)) {
                    int i = days.indexOf(time);
                    objects[i + 1] = count;
                }
            } else {
                dataList.add(objects);

                objects = new Object[days.size() + 1];
                for(int i = 0; i < days.size() + 1; i++) {
                    objects[i] = " ";
                }

                if (days.contains(time)) {
                    int i = days.indexOf(time);
                    objects[i + 1] = count;
                }

                currentCcrNo = ccrNo;
                objects[0] = ccrNo;
            }

        }

        ExportExcel ex = new ExportExcel(title, rowsName, dataList);
        String path= ex.export();
        if(!StringHelper.isTrimEmpty(path)){
            try {
                InputStream inStream = new FileInputStream(path);// 文件的存放路径
                // 设置输出的格式
                response.reset();
                response.setContentType("application/ms-excel;charset=UTF-8");
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sdf.format(date),"UTF-8")  + ".xls");
                // 循环取出流中的数据
                byte[] b = new byte[100];
                int len;
                try {
                    while ((len = inStream.read(b)) > 0)
                        response.getOutputStream().write(b, 0, len);
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

//    @RequestMapping(value = "/export2", method = RequestMethod.GET)
//    void export2(@RequestParam("month") String month,
//                 HttpServletResponse response) throws Exception {
//        String title = month + "统计数据";
//        Date monthDate = HzhrDateUtil.strToDate(month, "yyyy-MM");
//        Date nextMonthDate = HzhrDateUtil.addMonth(monthDate, 1);
//        List<String> days = HzhrDateUtil.getDayBetween(HzhrDateUtil.dateToStr(monthDate, "yyyy-MM-dd"), HzhrDateUtil.dateToStr(nextMonthDate, "yyyy-MM-dd"));
//        String[] rowsName = new String[]{"厂家","日期","未上传数量", "总数量", "上传成功率"};
//        List<Object[]> dataList = new ArrayList<Object[]>();
//
//        List<String> companyNames = reportMapper.select1();
//        for (String companyName :
//        companyNames) {
//            int i = 0;
//            for (String day :
//            days) {
//                String c1 = "-";
//                if (i == 0) {
//                    c1 = companyName;
//                }
//
//                Long time1 = HzhrDateUtil.strToDate(day, "yyyy-MM-dd").getTime();
//                Long time2 = HzhrDateUtil.addDay(new Date(time1), 1).getTime();
//                Map<String, Object> param = new HashMap<>();
//                param.put("param1", time1);
//                param.put("param2", companyName);
//                int count1 = reportMapper.select2(param);
//
//                param = new HashMap<>();
//                param.put("param1", time1);
//                param.put("param2", time1);
//                param.put("param3", time2);
//                param.put("param4", companyName);
//                int count2 = reportMapper.select3(param);
//
//                Integer c4 = 0;
//                if (count1 != 0) {
//                    BigDecimal b = new BigDecimal(count1 - count2).divide(new BigDecimal(count1), 2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
//                    c4 = b.intValue();
//                }
//
//                Object[] objects = new Object[]{c1, day, count2, count1, c4.toString() + "%"};
//                dataList.add(objects);
//                i++;
//            }
//        }
//
//
//
//        ExportExcel ex = new ExportExcel(title, rowsName, dataList);
//        String path= ex.export();
//        if(!StringHelper.isTrimEmpty(path)){
//            try {
//                InputStream inStream = new FileInputStream(path);// 文件的存放路径
//                // 设置输出的格式
//                response.reset();
//                response.setContentType("application/ms-excel;charset=UTF-8");
//                Date date = new Date();
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
//                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sdf.format(date),"UTF-8")  + ".xls");
//                // 循环取出流中的数据
//                byte[] b = new byte[100];
//                int len;
//                try {
//                    while ((len = inStream.read(b)) > 0)
//                        response.getOutputStream().write(b, 0, len);
//                    inStream.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }
}
